﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Lon.IO.Ports
{
    public abstract class PortBase<T> : IPort<T>
    {
        protected abstract  BusOpt<T> Bus
        {
            get;
        }                           
  
        IListener<T> listener = null;
        private string portName = "";
        private bool opened = false;

        public string PortName
        {
            get { return portName; }
            set { portName = value; }
        }
          
        public bool IsOpen()
        {
            return opened;
        }

        public PortBase():this("PortSimple",null)
        {
           
        }
        public PortBase(IFilter<T> fliter)
            : this("PortSimple",fliter)
        {
          
        }

        public PortBase(String portName)
            : this(portName, null)
        {

        }

        public PortBase(String portName, IFilter<T> rxFliter)
        {
            this.portName = portName;
            listener = new ListenerBase<T>();
            listener.RxFliter = rxFliter;
        }

        public bool Open()
        {
            if (this.listener == null) return false;
            //如已添加过不能重复添加
            if (this.opened == true) return true;
            Bus.AddListener(this.listener);
            this.opened = true;
            return true;
        }

        public bool Close()
        {
            if (!this.opened) return true;
            this.opened = false;
            Bus.DelListener(this.listener);
            return true;
        }



        //public abstract static void Write(T val);
        //{
        //      //Bus.Write(val);
        //}
      
        public AutoResetEvent RxEvent
        {
            get
            {
                if (this.listener == null) return null;
                else return this.listener.RxEvent;
            }
        }

        public bool Read(ref T val, int timeOut)
        {
            if (opened == false) return false;
            else return this.listener.Read(ref val, timeOut);
        }
        /// <summary>
        /// 读取一个值，无限期等待
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public bool Read(ref T val)
        {
            return Read(ref val,Timeout.Infinite);
        }

        public int BufLen
        {
            get
            {
                if (listener == null) return 0;
                else return listener.BufLen;
            }
            set
            {
                if (listener == null) return ;
                else  listener.BufLen=value;
            }
        }

        public void ClrBuffer()
        {
            if (listener == null) return;
            else listener.ClrBuffer();
        }
    }
}
